import { trim, filter } from 'lodash';
import { Op } from 'sequelize';
import BaseController from './base';
import SysMenuModel from '../models/sys-menu';

function getChildrenMenus(menu, menus) {
  const rows = filter(menus, { parent_code: menu.code });
  menu.hasChildren = false;
  if (rows.length > 0) {
    menu.children = rows;
    menu.hasChildren = true;
    for (const row of rows) {
      getChildrenMenus(row, menus);
    }
  }
}

// order docs https://sequelize.org/docs/v6/core-concepts/model-querying-basics/
class SysMenuController extends BaseController {
  getModel() {
    return SysMenuModel;
  }

  async findAll(req, res, next) {
    try {
      const menus = await SysMenuModel.findAll({ order: [['sequence', 'ASC'], ['code', 'ASC']], raw: true });
      const rows = filter(menus, { parent_code: 0 });
      for (const row of rows) {
        getChildrenMenus(row, menus);
      }

      res.sendOk({
        rows
      });
    }
    catch (e) {
      next(e);
    }
  }
}

export default new SysMenuController();
